<?php 
global $_GPC, $_W;
$shopid=check_right(3);
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id='".$shopid."'");
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
load()->model('mc');
if($operation=="display"){
	$cfg = $this->module['config'];
	load()->func('tpl');
	
	
} elseif ($operation == 'post') {
    $cfg = $this->module['config'];
	$wxcard=array();
	if(isset($_GPC['wxcard-key'])){
		foreach ($_GPC['wxcard-key'] as $index => $row) {
			if(empty($row))continue;
			$wxcard[$row]=$_GPC['wxcard-val'][$index];
		}
	}
	$parama=array();
	if(isset($_GPC['parama-key'])){
		foreach ($_GPC['parama-key'] as $index => $row) {
			if(empty($row))continue;
			$parama[$row]['value']=urlencode($_GPC['parama-val'][$index]);
			$parama[$row]['color']=$_GPC['parama-color'][$index];
		}
	}
	$settings = array(
		'debug' => intval($_GPC['debug']),
		'softkey' => trim($_GPC['softkey']),
		'appid' => trim($_GPC['appid']),
		'sub_appid' => trim($_GPC['sub_appid']),
		'sub_mch_id' => trim($_GPC['sub_mch_id']),
		'logo' => trim($_GPC['logo']),
		'appsecret' => trim($_GPC['appsecret']),
		'pay_name' => $_GPC['pay_name'],
		'pay_mchid' => $_GPC['pay_mchid'],
		'pay_signkey' => $_GPC['pay_signkey'],
		'pay_ip' => $_GPC['pay_ip'],
		'notify_url' => $_GPC['notify_url'],
		'wxcard' =>json_encode($wxcard),
		/*支付宝参数*/
		'app_id' => trim($_GPC['app_id']),
		'alipid' => trim($_GPC['alipid']),
		'charset' => "GBK",
		'alipay_key'=>preg_replace('/\s/','',$_GPC['alipay_key']),
		'alipay_cert'=>preg_replace('/\s/','',$_GPC['alipay_cert']),
		'appauthtoken'=>trim($_GPC['appauthtoken']),
		'gatewayUrl' => trim($_GPC['gatewayUrl']) ? trim($_GPC['gatewayUrl']) :"https://openapi.alipay.com/gateway.do",
		/*模板消息*/
		'tempmsg_pay'=>trim($_GPC['tempmsg_pay']),
		'tempmsg_paycon'=>htmlspecialchars_decode($_GPC['tempmsg_paycon']),
		
		'tempmsg_payparama'=>urldecode(json_encode($parama)),
		/*坐席限制*/
		'groupnum' => intval($_GPC['groupnum']),
		'usernum' => intval($_GPC['usernum']),
		/*积分*/
		'qrcode' => strval($_GPC['qrcode']),
		'credit' => floatval($_GPC['credit']),
		/*退款*/
		'tempmsg_refunder'=>trim($_GPC['tempmsg_refunder']),
		/*加密密匙*/
		'encryptcode'=>trim($_GPC['encryptcode']) ? trim($_GPC['encryptcode']) : "jetsum_money",
		/**/
		'wxmembercard' => trim($_GPC['wxmembercard']),
		
		'tempmsg_paycode' => trim($_GPC['tempmsg_paycode']),
		'ispaycode' => intval($_GPC['ispaycode']),
		'isgeneralbalance' => intval($_GPC['isgeneralbalance']),
		'helplink' => trim($_GPC['helplink']),
		
		'returnstr' => htmlspecialchars_decode($_GPC['returnstr']),
		'rule_id' => trim($_GPC['rule_id']),
		'floder' => trim($_GPC['floder']),

        'isgetmembercard' => intval($_GPC['isgetmembercard']),
        'getmembercardinfo' => htmlspecialchars_decode($_GPC['getmembercardinfo']),

        'isbank' => intval($_GPC['isbank']),
        'bankmch_id' => trim($_GPC['bankmch_id']),
        'bankpaykey' => trim($_GPC['bankpaykey']),
        'mch_create_ip' => trim($_GPC['mch_create_ip']),
        'tempmsg_memberpay' => trim($_GPC['tempmsg_memberpay']),

	);
	$settings['rootca']=$_GPC['rootca2'];
	$settings['apiclient_cert']=$_GPC['apiclient_cert2'];
	$settings['apiclient_key']=$_GPC['apiclient_key2'];
    foreach($cfg as $key=>$val){
        if(!isset($settings[$key])){
            $settings[$key]=$val;
        }
    }
	$this->saveSettings($settings);
    die();
	//die(json_encode(array("success"=>true)));
} elseif ($operation == 'uploadpem') {
    $filename="";
    load()->func('file');
    $dir_url='../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/";
    mkdirs($dir_url);
    $cfg = $this->module['config'];
    if ($_FILES["rootca"]["name"]){
        if(file_exists($dir_url.$cfg["rootca"]))@unlink ($dir_url.$cfg["rootca"]);
        $filename=TIMESTAMP.".pem";
        move_uploaded_file($_FILES["rootca"]["tmp_name"],$dir_url.$filename);
    }
    if ($_FILES["apiclient_cert"]["name"]){
        if(file_exists($dir_url.$cfg["apiclient_cert"]))@unlink ($dir_url.$cfg["apiclient_cert"]);
        $filename="cert".TIMESTAMP.".pem";
        move_uploaded_file($_FILES["apiclient_cert"]["tmp_name"],$dir_url.$filename);
    }
    if ($_FILES["apiclient_key"]["name"]){
        if(file_exists($dir_url.$cfg["apiclient_key"]))@unlink ($dir_url.$cfg["apiclient_key"]);
        $filename="key".TIMESTAMP.".pem";
        move_uploaded_file($_FILES["apiclient_key"]["tmp_name"],$dir_url.$filename);
    }
    die(json_encode(array("success"=>true,"filename"=>$filename)));
} elseif ($operation == 'postsetmember') {
	$cfg = $this->module['config'];
	if(!$cfg['wxmembercard'])die(json_encode(array("success"=>false,"msg"=>"请先填写微信会员卡卡号")));
	load()->func('communication');
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	$tokens=$acc->fetch_token();
	$data=array(
		"rule_info"=>array(
			"type"=> "RULE_TYPE_PAY_MEMBER_CARD",
			"base_info"=>array(
				"mchid_list"=>array($cfg['pay_mchid']),
				"begin_time"=>TIMESTAMP,
			  	"end_time"=>TIMESTAMP+(365*86400),
			),

			"member_rule"=>array(
				"card_id"=>$cfg['wxmembercard'],
				"least_cost"=>1,
				"max_cost"=>999999,
			)
		)
	);
	$pageparama=urldecode(json_encode($data));
	$resp = ihttp_request("https://api.weixin.qq.com/card/paygiftcard/add?access_token=".$tokens,$pageparama, $xml);
	$result=@json_decode($resp['content'],true);
	if(!$result['errcode']){
		die(json_encode(array("success"=>true,"rule_id"=>$result['rule_id'])));
	}else{
		die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));
	}
} elseif ($operation == 'postSetMember2') {
	$cfg = $this->module['config'];
	if(!$cfg['rule_id'])die(json_encode(array("success"=>false,"msg"=>"没有可删除的规则")));
	load()->func('communication');
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	$tokens=$acc->fetch_token();
	$data=array(
		"rule_id"=>$cfg['rule_id']
	);
	$pageparama=urldecode(json_encode($data));
	$resp = ihttp_request("https://api.weixin.qq.com/card/paygiftcard/delete?access_token=".$tokens,$pageparama, $xml);
	$result=@json_decode($resp['content'],true);
	if(!$result['errcode']){
		die(json_encode(array("success"=>true)));
	}else{
		die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));
	}
} elseif ($operation == 'setmemberactive1') {
    load()->func('communication');
    $cfg = $this->module['config'];
    $cardid=$cfg["wxmembercard"];
    if(!$cardid)die(json_encode(array("success"=>false,"msg"=>"请先填写会员卡ID并保存后操作")));
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $data=array(
        "card_id"=>$cardid,
        "member_card"=>array(
            "wx_activate"=>true,
            "wx_activate_after_submit"=>true,
            "wx_activate_after_submit_url"=>$_W["siteroot"]."app/index.php?i=".$_W["uniacid"]."&c=entry&do=membercardactive&m=j_hmoney",
        ),
    );
    $pageparama=urldecode(json_encode($data));
    $resp = ihttp_request("https://api.weixin.qq.com/card/update?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if(!$result['errcode']){
        die(json_encode(array("success"=>true)));
    }else{
        die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));
    }
} elseif ($operation == 'setmemberactive2') {
    load()->func('communication');
    $cfg = $this->module['config'];
    $cardid=$cfg["wxmembercard"];
    if(!$cardid)die(json_encode(array("success"=>false,"msg"=>"请先填写会员卡ID并保存后操作")));
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $data=array(
        "card_id"=>$cardid,
        "member_card"=>array(
            "wx_activate"=>true,
            "wx_activate_after_submit"=>false,
        ),
    );
    $pageparama=urldecode(json_encode($data));
    $resp = ihttp_request("https://api.weixin.qq.com/card/update?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if(!$result['errcode']){
        die(json_encode(array("success"=>true)));
    }else{
        die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));
    }
} elseif ($operation == 'SetMembername') {
	$memberid=$cfg["wxmembercard"];
	if(!$memberid)die(json_encode(array("success"=>false,"msg"=>"请先填写会员卡的ID")));
	load()->func('communication');
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	$tokens=$acc->fetch_token();
	$url = "https://api.weixin.qq.com/card/update?access_token=".$tokens;
	$data=array(
		"card_id"=>$memberid,
		"member_card"=>array(
			"supply_bonus"=>true,
			"custom_field1"=>array(
				"name"=>urlencode("金额"),
				"name_type"=>"FIELD_NAME_TYPE_STAMP",
				"url"=>"",
			),
		),
	);
	$content = ihttp_post($url,urldecode(json_encode($data)));
	$result = @json_decode($content['content'], true);
	if($result['errcode'])die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));
	if($result['send_check']){
		die(json_encode(array("success"=>true)));
	}else{
		die(json_encode(array("success"=>true)));
	}
}
include $this->template('web/'.$cfg['floder'].'/settings');